package com.ming.seatMonitoring.controller;

/**
 * @author 小明
 * @date 2021/10/23
 * @description
 */
import com.ming.seatMonitoring.mapper.FileMapper;
import com.ming.seatMonitoring.pojo.entity.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.UUID;

/**
 * 图片上传和发布接口
 */
@RestController
public class FileController {

    @Autowired
    FileMapper fileMapper;
    //服务器ip
    String path = "39.103.205.130";

    @RequestMapping(value = "/picUpload")
    public ResultBody fileUpload(@RequestParam(value = "file") MultipartFile file,@RequestParam int roomId, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            ResultBody.error().message("文件为空");
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".jpg"));
        // 上传后的路径
        String filePath = "C://temp-seat//";
        // 新文件名
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "http://"+path+":9010/img/" + fileName;
        fileMapper.setPhoto(roomId,filename);
        model.addAttribute("filename", filename);
        System.out.println(fileName);
        System.out.println(model);
        return ResultBody.ok().message("图片上传成功");
    }

    @GetMapping("/getFile")
    public ArrayList<String> findphoto(Model model) throws IOException {
        File f = new File("C:\\temp-seat");
        final ArrayList<String> list = new ArrayList<>();
        if (!f.exists()) {
            f.createNewFile();
        }
        if (f.isDirectory()) {
            for (File file : f.listFiles()) {
                if (file.isFile() && file.getName().endsWith(".jpg")) {
                    list.add("/img/"+file.getName());
                }
            }
        }
        return list;

    }
}
